package ActivityPractice;

/**
 * Created by 蜡笔小新丶 on 2017/10/9.
 */

public class LinkedStack<T> implements Stack<T>
{
    private int num;
    private LinearNode<T> Next;

    public LinkedStack()
    {
        num = 0;
        Next = null;
    }

    public void push (T element)
    {
        LinearNode<T> temp = new LinearNode<T> (element);

        temp.setNext(Next);
        Next = temp;
        num++;
    }

    public T pop() throws Exception
    {
        if (isEmpty())
            throw new Exception("Stack");

        T result = Next.getElement();
        Next = Next.getNext();
        num--;

        return result;
    }

    public T peek() throws Exception
    {
        if (isEmpty())
            throw new Exception("Stack");

        return Next.getElement();
    }

    public boolean isEmpty()
    {
        return (num == 0);
    }

    public int size()
    {
        return num;
    }

    public String toString()
    {
        String result = "";
        LinearNode current = Next;

        while (current != null)
        {
            result = result + (current.getElement()).toString() + "\n";
            current = current.getNext();
        }

        return result;
    }
}

